import React, { useState, useEffect } from "react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Filter, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ConstructionMethodTemplateAPI } from "@/api/ConstructionMethodTemplate";
import { ensureArray } from "@/utils/ensureArray"; // 引入主组件中使用的安全数组函数

export default function SchemeFilters({
  filters,
  onFilterChange, // 主组件传递的回调：(key, value) => void
  projects,
  disabled, // 从主组件接收禁用状态（如离线时）
}) {
  const [constructionMethods, setConstructionMethods] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  // 加载施工方法模板（优化：增加错误处理和重试）
  useEffect(() => {
    const fetchConstructionMethods = async () => {
      if (disabled) return; // 离线时不请求
      try {
        setIsLoading(true);
        const response = await ConstructionMethodTemplateAPI.getList();
        const methods = ensureArray(response.data).map(method => ({
          id: method.id || method.methodName, // 兼容可能的ID缺失
          methodName: method.methodName || `未命名方法-${method.id}`
        }));
        setConstructionMethods(methods);
      } catch (error) {
        setConstructionMethods([]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchConstructionMethods();
  }, [disabled]);

  // 处理筛选变更：转换为 (key, value) 格式传递给主组件
  const handleFilterChange = (key, value) => {
    if (disabled) return; // 禁用状态不处理
    onFilterChange(key, value); // 关键修正：传递键和值，而非对象
  };

  // 清空所有筛选条件
  const handleClearFilters = () => {
    handleFilterChange("projectId", "all");
    handleFilterChange("constructionMethod", "all");
    handleFilterChange("approvalStatus", "all");
  };

  // 判断是否有活跃的筛选条件
  const hasActiveFilters = Object.values(filters).some(value => value !== "all");

  return (
    <div className="flex gap-3 flex-wrap items-center">
      {/* 筛选图标 */}
      <Filter className="w-4 h-4 text-gray-500 shrink-0" />

      {/* 项目筛选 */}
      <Select
        value={filters.projectId || "all"}
        onValueChange={(value) => handleFilterChange("projectId", value)}
        disabled={disabled}
      >
        <SelectTrigger className="w-40">
          <SelectValue placeholder="项目" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">全部项目</SelectItem>
          {ensureArray(projects)
            .filter(project => 
              project?.id && project?.projectName // 只显示有ID和名称的有效项目
            )
            .map(project => (
              <SelectItem key={project.id} value={project.id}>
                {project.projectName}
              </SelectItem>
            ))}
        </SelectContent>
      </Select>

      {/* 施工方法筛选 */}
      <Select
        value={filters.constructionMethod || "all"}
        onValueChange={(value) => handleFilterChange("constructionMethod", value)}
        disabled={isLoading || disabled}
      >
        <SelectTrigger className="w-40">
          <SelectValue placeholder="施工方法" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">全部方法</SelectItem>
          {isLoading ? (
            <SelectItem value="loading" disabled>加载中...</SelectItem>
          ) : ensureArray(constructionMethods).length > 0 ? (
            constructionMethods.map(method => (
              <SelectItem key={method.id} value={method.id}>
                {method.methodName}
              </SelectItem>
            ))
          ) : (
            <SelectItem value="none" disabled>无施工方法数据</SelectItem>
          )}
        </SelectContent>
      </Select>

      {/* 审批状态筛选 */}
      <Select
        value={filters.approvalStatus || "all"}
        onValueChange={(value) => handleFilterChange("approvalStatus", value)}
        disabled={disabled}
      >
        <SelectTrigger className="w-32">
          <SelectValue placeholder="审批状态" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">全部状态</SelectItem>
          <SelectItem value="notStarted">未开工</SelectItem>
          <SelectItem value="inProgress">已开工</SelectItem>
          <SelectItem value="completed">已完工</SelectItem>
          {/* 补充主组件中存在的其他状态，确保全覆盖 */}
          {/* <SelectItem value="draft">草稿</SelectItem>
          <SelectItem value="submitted">审批中</SelectItem>
          <SelectItem value="approved">已批准</SelectItem>
          <SelectItem value="rejected">已驳回</SelectItem> */}
        </SelectContent>
      </Select>

      {/* 清空筛选按钮（有活跃筛选时显示） */}
      {hasActiveFilters && (
        <Button
          variant="ghost"
          size="sm"
          onClick={handleClearFilters}
          disabled={disabled}
          className="text-gray-500 hover:text-gray-700"
        >
          <X className="w-4 h-4 mr-1" /> 清空筛选
        </Button>
      )}
    </div>
  );
}